package config

import (
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"sync"
)

var (
	config GlobalConfig
	once   sync.Once
)

type SvrConfig struct {
	SvrName string `mapstructure:"svr_name"`
	Port    int    `mapstructure:"port"`
}

type DBConfig struct {
	Url         string `mapstructure:"url"`
	User        string `mapstructure:"user"`          // 用户名
	Password    string `mapstructure:"password"`      // 密码
	DBName      string `mapstructure:"dbname"`        // db名
	MaxIdleConn int    `mapstructure:"max_idle_conn"` // 最大空闲连接数
	MaxOpenConn int    `mapstructure:"max_open_conn"` // 最大打开的连接数
	MaxIdleTime int    `mapstructure:"max_idle_time"` // 连接最大空闲时间
}

type RedisConfig struct {
	Url string `mapstructure:"url"`
}

type MongodbConfig struct {
	Url      string `mapstructure:"url"`
	Database string `mapstructure:"database"`
}

type GlobalConfig struct {
	SvrConfig     SvrConfig     `mapstructure:"svr_config"`
	DbConfig      DBConfig      `mapstructure:"db"`
	RedisConfig   RedisConfig   `mapstructure:"redis"`
	MongodbConfig MongodbConfig `mapstructure:"mongodb"`
}

func GetGlobalConfig() *GlobalConfig {
	once.Do(readConfig)
	return &config
}

func readConfig() {
	viper.SetConfigType("yml")
	viper.SetConfigFile("./src/config/config.yaml")

	err := viper.ReadInConfig()
	if err != nil {
		panic("read config file error  : " + err.Error())
	}

	err = viper.Unmarshal(&config)
	if err != nil {
		panic("config file unmarshal error : " + err.Error())
	}

	log.Infof("config === %+v", config)
}
